package com.kehutong.charge.service.impl;

import com.kehutong.charge.dao.ChargeBillHouseDao;
import com.kehutong.charge.dao.ChargeOrderDao;
import com.kehutong.charge.dto.ChargeBillItemAppDTO;
import com.kehutong.charge.dto.ChargeBillItemDTO;
import com.kehutong.charge.entity.ChargeBillItems;
import com.kehutong.charge.entity.ChargeOrderItem;
import com.kehutong.charge.entity.ChargeOrderManage;
import com.kehutong.charge.entity.ChargePenaltyOrder;
import com.kehutong.charge.service.ChargeOrderItemService;
import com.kehutong.charge.service.ChargePenaltyService;
import com.kehutong.charge.util.CommonClient;
import com.kehutong.charge.util.enums.ChargeBillStatusEnum;
import com.kehutong.charge.util.enums.ChargeOrderStatusEnum;
import com.kehutong.charge.util.enums.CommonEnum;
import com.kehutong.common.enums.UserType;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import org.coraframework.converter.util.StringUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.PageCondition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.util.List;

/**
 * @author joneRon
 * @Title: kht
 * @Description: 子订单管理
 * @date 2021/8/9
 */
public class ChargeOrderItemServiceImpl implements ChargeOrderItemService {

    private static final Logger logger = LoggerFactory.getLogger(ChargeOrderItemServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    CommonClient commonClient;
    @Inject
    ChargeOrderDao chargeOrderDao;

    @Override
    public Page<ChargeOrderItem> findPage(JSONObject jsonObject) {
        FindPage<ChargeOrderItem> find = jdbcSession.findPage(ChargeOrderItem.class);
        find.eq("deleted", false);
        find.eq(jsonObject,"orderNo");
        //添加选中导出条件
        JSONArray exportIdList = jsonObject.getJSONArray("exportIdList");
        if(!Objects.isEmpty(exportIdList)){
            find.in("itemBillNo",exportIdList);
        }

        find.order("createTime", "desc");

        find.page(jsonObject);
        return find.exe();
    }

    @Override
    public List<ChargeOrderItem> findList(JSONObject jsonObject) {

        return jdbcSession.findArray(ChargeOrderItem.class)
                .eq("deleted", false)
                .eq(jsonObject,"userNo")
                .eq(jsonObject,"houseNo")
                .eq(jsonObject,"orderNo")
                .eq(jsonObject,"itemBillNo")
                .eq(jsonObject,"houseBillNo")
                .eq(jsonObject,"orderStatus")
                .eq(jsonObject,"optStatus")
                .eq(jsonObject,"orderYearMonth")
                .exe();
    }

    @Override
    public Object save(ChargeOrderItem chargeOrderItem) throws Exception {

        List<ChargeOrderItem> itemList = jdbcSession.findArray(ChargeOrderItem.class)
                .eq("itemBillNo",chargeOrderItem.getOrderItemNo())
                .noEq("orderStatus",ChargeOrderStatusEnum.ORDER_CLOSE).exe();
        if(Objects.nonEmpty(itemList)){
            return Result.error(123,"订单已经存在！");
        }

        ChargeBillItems items = jdbcSession.findOne(ChargeBillItems.class)
                .eq("itemBillNo",chargeOrderItem.getItemBillNo()).exe();

        if(null != items){
            chargeOrderItem.setOrderAmount(items.getBillAmount());
            chargeOrderItem.setPayableAmount(items.getBillAmount());
            chargeOrderItem.setHouseNo(items.getHouseNo());
            chargeOrderItem.setBuildNo(items.getBuildNo());
            chargeOrderItem.setCommunityNo(items.getCommunityNo());
            chargeOrderItem.setCommunityName(items.getCommunityName());
            chargeOrderItem.setBillAddress(items.getBillAddress());
            chargeOrderItem.setFeeTypeName(items.getFeeTypeName());
            chargeOrderItem.setFeeTypeNo(items.getFeeTypeNo());
            chargeOrderItem.setUsageNumber(items.getUsageNumber());
            chargeOrderItem.setOrderYearMonth(items.getBillYearMonth());
            chargeOrderItem.setHouseBillNo(items.getHouseBillNo());
            chargeOrderItem.setOrderStatus(ChargeOrderStatusEnum.ORDER_WAIT_PAY);
            chargeOrderItem.setOptStatus(ChargeOrderStatusEnum.ORDER_REFUND_NOT);
            chargeOrderItem.setResidentsType(items.getResidentsType());
            chargeOrderItem.setPayMethod(CommonEnum.COM_PAY_NOT);
        }else{
            //查询订单数据
            ChargeOrderManage orderManage = jdbcSession.findOne(ChargeOrderManage.class)
                    .eq("orderNo",chargeOrderItem.getOrderNo())
                    .eq("orderStatus",ChargeOrderStatusEnum.ORDER_WAIT_PAY).exe();

            chargeOrderItem.setPayableAmount(chargeOrderItem.getOrderAmount());
            chargeOrderItem.setBuildNo(orderManage.getBuildNo());
            chargeOrderItem.setCommunityNo(orderManage.getCommunityNo());
            chargeOrderItem.setCommunityName(orderManage.getCommunityName());
            chargeOrderItem.setBillAddress(orderManage.getBillAddress());
            chargeOrderItem.setOrderYearMonth(orderManage.getOrderYearMonth());
            chargeOrderItem.setHouseBillNo(orderManage.getHouseBillNo());
            chargeOrderItem.setOrderStatus(ChargeOrderStatusEnum.ORDER_WAIT_PAY);
            chargeOrderItem.setOptStatus(ChargeOrderStatusEnum.ORDER_REFUND_NOT);
            chargeOrderItem.setResidentsType(orderManage.getResidentsType());
            chargeOrderItem.setPayMethod(CommonEnum.COM_PAY_NOT);

            //违约金处理
            List<ChargePenaltyOrder> penaltyOrders = jdbcSession.findArray(ChargePenaltyOrder.class)
                    .eq("billStatus",ChargeBillStatusEnum.BILL_WAIT_PAID)
                    .eq("billYearMonth",orderManage.getOrderYearMonth())
                    .eq("houseNo",orderManage.getHouseNo()).exe();

            for (int i = 0; i < penaltyOrders.size(); i++) {
                ChargePenaltyOrder penaltyOrder = penaltyOrders.get(i);
                penaltyOrder.setPenaltyOrderNo(orderManage.getOrderNo());
                jdbcSession.updateById(penaltyOrder);
            }
        }

        return Result.success(jdbcSession.insert(chargeOrderItem));
    }

    @Override
    public Object update(ChargeOrderItem chargeOrderItem) throws Exception {

        return jdbcSession.updateById(chargeOrderItem);
    }

    @Override
    public Object deleteById(String id) {
        return null;
    }

    @Override
    public Object getObj(JSONObject jsonObject) {
        return jdbcSession.findOne(ChargeOrderItem.class)
                .eq(jsonObject,"orderItemNo")
                .eq(jsonObject,"optStatus")
                .exe();
    }

    @Override
    public Object findOrderItemList(JSONObject jsonObject, Token token) throws Exception {

        PageCondition query = Condition.createPage(false);

        query.eq("deleted", false);
        query.eq(jsonObject,"orderYearMonth");
        query.eq(jsonObject,"orderStatus");
        query.eq(jsonObject,"userNo");
        query.eq(jsonObject,"communityNo");
        query.eq(jsonObject,"buildNo");

        if(token.getUserType().equals(UserType.webwork)){
            JSONArray stewardHouseNos = commonClient.getStewardHouseNos(token.getUuid());
            query.in("houseNo",stewardHouseNos);

        }else {
            query.eq(jsonObject,"houseNo");
        }

        String search = jsonObject.getString("search");
        if(!Objects.isEmpty(search)){
            query.markBegin();
            query.like("communityName", search).or();
            query.like("chargeName", search).or();
            query.markEnd();
        }

        query.groupBy("houseNo");
        query.groupBy("userNo");
        query.page(jsonObject);

        return chargeOrderDao.findOrderItemList(query);
    }
}
